package com.ssm.controller;

import com.ssm.domain.SysLog;
import com.ssm.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAop {

    private Date visitTime;//开始时间
    private Class clazz;//访问的类
    private Method method;//访问的方法

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysLogService sysLogService;


    /**
     * @param : [jp]
     * @return : void
     * @Description : 前置通知，主要获取开始时间，执行的类上那一个。执行的方法是那一个方法
     */
    @Before("execution(* com.ssm.controller.*.*(..))")
    public void doBefore(JoinPoint jp) throws NoSuchMethodException {
        visitTime = new Date();//当前时间就是访问开始的时间

        clazz = jp.getTarget().getClass();//获取具体要访问的类

        String methodName = jp.getSignature().getName();//获取访问的方法名称

        Object[] args = jp.getArgs();//获取访问的方法的参数

        if (args == null || args.length == 0) {
            method = clazz.getMethod(methodName);//获取无参数的方法
        } else {
            Class[] classArgs = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                classArgs[i] = args[i].getClass();
            }
            clazz.getMethod(methodName, classArgs);
        }
    }


    /**
     * @param : []
     * @return : void
     * @Description : 后置通知
     */
    @After("execution(* com.ssm.controller.*.*(..))")
    public void doAfter() {
        //获取访问的时长
        long time = new Date().getTime() - visitTime.getTime();

        //获取url
        String url = "";
        if (clazz != null && method != null && clazz != SysLog.class) {

            //1、获取类上的@RequestMapping("/user")
            RequestMapping classAnnotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
            if (classAnnotation != null) {
                String[] classValue = classAnnotation.value();

                //2、获取方法上的@RequestMapping("/findAll.do")
                RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
                if (methodAnnotation != null) {
                    String[] methodValue = methodAnnotation.value();
                    url = classValue[0] + methodValue[0];
                }
            }
            //获取访问IP
            String ip = request.getRemoteAddr();

            //获取当前存在对象
            SecurityContext context = SecurityContextHolder.getContext();
            User user = (User) context.getAuthentication().getPrincipal();
            String username = user.getUsername();

            //将日志相关信息封装到SysLog中
            SysLog sysLog = new SysLog();
            sysLog.setExecutionTime(time);
            sysLog.setVisitTime(visitTime);
            sysLog.setIp(ip);
            sysLog.setUrl(url);
            sysLog.setUsername(username);
            sysLog.setMethod("[类名]" + clazz.getName() + "[方法名]" + method.getName());

            //目的是屏蔽操作添加查看日志时产生的日志
            if (clazz.getName() != "com.ssm.controller.SysLogController") {
                sysLogService.save(sysLog);
            }
        }
    }
}
